package main

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"net/http"
	"time"
)

func shopIndexHandler(c *gin.Context) {
	//沉睡五秒
	time.Sleep(5 * time.Second)
	c.JSON(http.StatusOK, gin.H{
		"code": 0,
		"msg":  "shopping/index",
	})
}

func shopHomeHandler(c *gin.Context) {
	time.Sleep(3 * time.Second)
	fmt.Println(c.MustGet("key").(string))
	c.JSON(http.StatusOK, gin.H{
		"code": 0,
		"msg":  "shopping/home",
	})
}

// 自定义钩子函数(中间件)
func castTime(c *gin.Context) {
	start := time.Now()
	//Gin 框架中的请求上下文中设置自定义的键值对数据
	c.Set("key", "value")
	//运行下一个Handler
	c.Next()

	//统计耗时
	cast := time.Since(start)
	fmt.Println("cast:", cast)
}

func main() {
	//Default相较于New启用两个中间件
	//1.logger 2. recover
	r := gin.Default()

	//使用自定义的中间件
	r.Use(castTime)

	shoppingGroup := r.Group("/shopping")
	{
		shoppingGroup.GET("/index", shopIndexHandler)
		shoppingGroup.GET("/home", shopHomeHandler)
	}
	r.Run()
}
